package com.sunedai.tiger.web.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * 公共拦截器，拦截请求参数
 * @author zhaolipeng
 */
@Slf4j
public class CommonInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info("请求IP：" + request.getRemoteAddr());
    log.info("请求链接：" + request.getRequestURL().toString());
    StringBuilder params = new StringBuilder();
    Set<Map.Entry<String, String[]>> entries = request.getParameterMap().entrySet();
    for (Map.Entry<String, String[]> entry : entries) {
      params.append(entry.getKey());
      params.append(":");
      params.append(Arrays.toString(entry.getValue()));
      params.append("||");
    }
    log.info("请求参数：[" + params.toString() + "]");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  }
}
